<template>
  <a-page-header :title="$t('250')">
    <template #extra>
      <a-input-search
        v-model:value="state.keyWord"
        :placeholder="$t('134')"
        @search="onSearch"
        @pressEnter="onSearch"
      />
      <a-button @click="loadShare" :title="$t('104')">{{ $t("104") }}</a-button>
    </template>
  </a-page-header>
  <a-table :columns="cols" :data-source="lstModel" bordered size="small">
    <template #bodyCell="{ column, text, record }">
      <template v-if="column.dataIndex === 'name'">
        <a href="#" @click="goViewModel(record)">{{ record.name }}</a>
        <span style="color: gray; font-size: smaller; margin-left: 8px">{{
          record.memo
        }}</span>
      </template>
    </template>
  </a-table>
  <a-modal
    v-model:open="state.popVisitRequest"
    :title="$t('251')"
    :footer="null"
    width="720px"
  >
    <a-alert :message="formVisitRequest.hint" type="info" closable />
    <p></p>
    <a-form :model="formVisitRequest" layout="vertical">
      <a-form-item :label="$t('252')">
        <a-select v-model:value="formVisitRequest.vgt">
          <a-select-option
            v-for="item in appStore.aryVgt"
            :key="item.key"
            :value="item.key"
            >{{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :label="$t('256')">
        <a-switch
          v-model:checked="formVisitRequest.writeAble"
          :disabled="CommonDefine.useful(channel.selectedModel.store)"
        />
      </a-form-item>
      <a-form-item :label="$t('255')">
        <VisitRightEditor ref="refVre"></VisitRightEditor>
      </a-form-item>
      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-button @click="getSample">示例记录</a-button>
        <span>&nbsp;&nbsp;</span>
        <a-button type="primary" @click="sentVisitReuqest">{{
          $t("257")
        }}</a-button>
      </a-form-item>
    </a-form>
    <table width="100%" v-if="state.showSample">
      <tr v-for="item in lstSampleRecord" :key="item['0']">
        <td>更新日期 {{ item["1"] }}</td>
        <td>{{ Utils.describeRecord(item) }}</td>
      </tr>
    </table>
  </a-modal>
  <a-drawer
    v-model:open="state.popModelView"
    :title="$t('110')"
    size="large"
    :bodyStyle="{ padding: '4px' }"
    :headerstyle="{ padding: '4px' }"
  >
    <a-flex gap="small" justify="flex-end">
      <a-button @click="subscribe" v-if="!channel.visitToken.subscribed"
        >订阅数据变更</a-button
      >
      <a-space v-else>
        <a-button @click="unSubscribe">取消订阅</a-button>
        <a-button @click="goSubscribe">更新概览</a-button>
      </a-space>
      <a-button type="primary" @click="goModelRecord">{{ $t("135") }}</a-button>
    </a-flex>
    <VisitGroupViewer :vg="channel.visitToken.vg"></VisitGroupViewer>
    <field-table ref="refFT" :modelId="channel.selectedModel.id"></field-table>
  </a-drawer>
  <a-modal
    v-model:open="state.popSubscription"
    title="更新概览"
    :footer="null"
    width="720px"
  >
    <a-descriptions size="small" :column="1" bordered>
      <a-descriptions-item label="新增记录">{{
        subscriptionInfo[0]
      }}</a-descriptions-item>
      <a-descriptions-item label="修改记录">{{
        subscriptionInfo[1]
      }}</a-descriptions-item>
      <a-descriptions-item label="删除记录">{{
        subscriptionInfo[2]
      }}</a-descriptions-item>
    </a-descriptions>
    <a-button @click="resetSubscribe">重置订阅</a-button>
  </a-modal>
</template>
<script setup>
import { nextTick, onMounted, reactive, ref } from "vue";
import CommonDefine from "@/component/CommonDefine";
import { useRouter } from "vue-router";
import JSEncrypt from "jsencrypt";
import FieldTable from "@/component/field/FieldTable.vue";
import Utils from "@/component/Utils";
import { useI18n } from "vue-i18n";
import VisitGroupViewer from "@/component/visit/VisitGroupViewer.vue";
import VisitRightEditor from "@/component/visit/ShareRuleOfModelEditor.vue";

const { t } = useI18n();
const router = useRouter();
const appStore = CommonDefine.appStore();
const channel = CommonDefine.channel();
const cols = [
  {
    title: t("128"),
    dataIndex: "authorName",
    sorter: (a, b) => {
      return a["authorName"].localeCompare(b["authorName"], "zh");
    },
  },
  {
    title: t("112"),
    dataIndex: "name",
    sorter: (a, b) => {
      return a["name"].localeCompare(b["name"], "zh");
    },
  },
  {
    title: t("258"),
    dataIndex: "visitorCount",
    sorter: (a, b) => {
      return a["visitorCount"].localeCompare(b["visitorCount"], "zh");
    },
  },
  {
    title: t("259"),
    dataIndex: "reqSum",
    sorter: (a, b) => {
      return a["reqSum"].localeCompare(b["reqSum"], "zh");
    },
  },
  {
    title: t("260"),
    dataIndex: "visitStatus",
    sorter: (a, b) => {
      return a["visitStatus"].localeCompare(b["visitStatus"], "zh");
    },
  },
];
const state = reactive({
  popVisitRequest: false,
  popModelView: false,
  popSubscription: false,
  keyWord: "",
  showSample: false /* 是否展现样例数据 */,
});
const formVisitRequest = reactive({});
const refFT = ref();
const lstModel = reactive([]);
const allShareModel = [];
const encryptor = new JSEncrypt();
encryptor.setPublicKey(appStore.pubKey);
const refVre = ref();
const subscriptionInfo = ref([0, 0, 0]);

const goViewModel = (share) => {
  channel.selectedModel = share.model;
  CommonDefine.apiPostArm(
    `/api/v1/share/check-auth/${channel.selectedModel.id}`,
    null,
    (d) => {
      if (d.pass) {
        channel.visitToken = d;
        loadVisitDetail();
      } else {
        if (d.vr) {
          Object.assign(formVisitRequest, d.vr);
          if (d.vr.acceptTs) {
            formVisitRequest.hint = t("261");
          } else {
            formVisitRequest.hint = t("262");
          }
        } else {
          formVisitRequest.hint = t("263");
        }
        state.popVisitRequest = true;
      }
    }
  );
};

// 加载访问上下文，包括模型字段列表，访问组
const loadVisitDetail = () => {
  let fn = (fields) => {
    state.popModelView = true;
    nextTick(() => {
      if (refFT.value) {
        refFT.value.loadField();
      }
    });
  };
  CommonDefine.runWithFieldCache(channel.selectedModel.id, fn);
};

const loadShare = () => {
  CommonDefine.clearArray(lstModel);
  CommonDefine.clearArray(allShareModel);
  CommonDefine.apiGetArm("/api/v1/share/all", (d) => {
    d.forEach((item) => {
      item.authorName = Utils.getUserName(item.model.uid);
      item.name = item.model.name;
      item.memo = item.model.memo;
      lstModel.push(item);
      allShareModel.push(item);
    });
  });
};

const sentVisitReuqest = () => {
  formVisitRequest.modelId = channel.selectedModel.id;
  formVisitRequest.rights = refVre.value.getRules();
  CommonDefine.apiPostArm(
    `/api/v1/share/send-request`,
    formVisitRequest,
    (d) => {
      CommonDefine.alert(t("264"));
      state.popVisitRequest = false;
    }
  );
};

const goModelRecord = () => {
  router.push("/index/share-model-record");
};

const onSearch = () => {
  CommonDefine.clearArray(lstModel);
  if (CommonDefine.isStringValue(state.keyWord)) {
    allShareModel.forEach((item) => {
      if (
        item.model.name.indexOf(state.keyWord) >= 0 ||
        (item.model.memo && item.model.memo.indexOf(state.keyWord) >= 0)
      ) {
        lstModel.push(item);
      }
    });
  } else {
    allShareModel.forEach((item) => lstModel.push(item));
  }
};

const subscribe = () => {
  CommonDefine.apiPostArm(
    `/api/v1/share/subscribe-changes/${channel.selectedModel.id}`,
    null,
    (d) => {
      CommonDefine.alert("订阅数据变动成功");
      channel.visitToken.subscribed = true;
    }
  );
};

const unSubscribe = () => {
  CommonDefine.apiPostArm(
    `/api/v1/share/cancel-subscribe/${channel.selectedModel.id}`,
    null,
    (d) => {
      CommonDefine.alert("取消订阅成功");
      channel.visitToken.subscribed = false;
    }
  );
};

const goSubscribe = () => {
  CommonDefine.apiGetArm(
    `/api/v1/record/subscription-overview/${channel.selectedModel.id}`,
    (d) => {
      subscriptionInfo.value = d;
      state.popSubscription = true;
    }
  );
};

const resetSubscribe = () => {
  CommonDefine.apiPostArm(
    `/api/v1/share/reset-subscription/${channel.selectedModel.id}`,
    null,
    (d) => {
      CommonDefine.alert("重置订阅成功,在此之前的订阅内容已被删除。");
    }
  );
};

const lstSampleRecord = reactive([]);

/* 获取样例数据 */
const getSample = () => {
  CommonDefine.clearArray(lstSampleRecord);
  CommonDefine.apiGetArm(
    `/api/v1/share/sample/${channel.selectedModel.id}`,
    (d) => {
      d.data.forEach((x) => {
        lstSampleRecord.push(x.display);
      });
      state.showSample = true;
    }
  );
};

onMounted(() => {
  loadShare();
});
</script>
